package kr.hkit.androidcomplete03.ch28;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.util.ArrayList;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import kr.hkit.androidcomplete03.R;
import kr.hkit.androidcomplete03.ch28.common.Item;
import kr.hkit.androidcomplete03.ch28.common.MyAdapter;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;

public class XMLPULLParser extends Activity {
	
	ListView lists;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.parser);
		lists = (ListView)findViewById(R.id.orderListView);
		new ParsingXml().execute("order.xml");
	}
	
	private class ParsingXml extends AsyncTask<String, Void, ArrayList<Item>>{

		ProgressDialog progressDlg;

		@Override
		protected void onPreExecute() {
			Log.d("TAG", "XMLPULLParser _ onPreExecute()");
			progressDlg = ProgressDialog.show(XMLPULLParser.this, "Wait", "order.xml Parsing...");
		}
		
		@Override
		protected void onPostExecute(ArrayList<Item> result) {
			Log.d("TAG", "XMLPULLParser _ onPostExecute()");
			MyAdapter adapter = new MyAdapter(XMLPULLParser.this, R.layout.listrow, result);
			lists.setAdapter(adapter);
			progressDlg.dismiss();
		}
		
		@Override
		protected ArrayList<Item> doInBackground(String... params) {
			Log.d("TAG", "XMLPULLParser _ doInBackground()");
			StringBuilder sb = new StringBuilder();
			String str = null;
			BufferedReader br = null;
			
			try {
				br = new BufferedReader(new InputStreamReader(openFileInput(params[0])));
				while((str=br.readLine()) != null){
					sb.append(str);
				}
			} catch (FileNotFoundException e) {
				
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			return parsingXml(sb.toString());
		}
		
		private ArrayList<Item> parsingXml(String xml){
			Log.d("TAG", "XMLPULLParser _ parsingXml()");
			final String TAG="XML PULL Parser";
			ArrayList<Item> arLists = new ArrayList<>();
			Item item = null;
			boolean initItem = false;
			
			XmlPullParserFactory factory;
			
			try {
				factory = XmlPullParserFactory.newInstance();
				XmlPullParser parser = factory.newPullParser();
				parser.setInput(new StringReader(xml));
				
				int eventType = parser.getEventType();
				
				// 끝까지 반복
				while(eventType != XmlPullParser.END_DOCUMENT){
					switch(eventType){
					case XmlPullParser.START_DOCUMENT:
						Log.d("TAG", "START_DOCUMENT");
						break;
						
					case XmlPullParser.END_DOCUMENT:
						Log.d("TAG", "END_DOCUMENT");
						break;
						
					case XmlPullParser.TEXT:	
						Log.d("TAG", "TEXT");
						if (initItem){
							item.setItemName(parser.getText());
							//initItem = false;
						}
						break;
						
					case XmlPullParser.START_TAG: 	// <item> 시작
						Log.d("TAG", "START_TAG");
						if (parser.getName().equalsIgnoreCase("item")){
							item = new Item();
							initItem = true;
						}
						//속성이 존재한다면 반드시 여기서 추출
						if (parser.getAttributeCount()>0){
							for(int i=0; i<parser.getAttributeCount(); i++){
								if (parser.getAttributeName(i).equalsIgnoreCase("price")){
									item.setItemPrice(Integer.parseInt(parser.getAttributeValue(i)));
								}else{
									item.setItemMaker(parser.getAttributeValue(i));
								}
							}
						}

						break;
						
					case XmlPullParser.END_TAG:		// </item>
						Log.d("TAG", "END_TAG");
						if (parser.getName().equalsIgnoreCase("item")){
							initItem = false;
							arLists.add(item);
						}
						break;
					}
					eventType = parser.next();
				}
			} catch (XmlPullParserException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			return arLists;
		}
	}
}
